﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using KL.UFrame.Core.Exception;
using KL.UFrame.Core.Result;
using KL.UFrame.Data.Entities;
using KL.UFrame.Data.Models;

namespace KL.UFrame.Data.Business.Impl
{
    public class PerformanceBusiness:BusinessBase, IPerformanceBusiness
    {
        public async Task<int> CreateAsync(PerformanceModel model)
        {
            var item = new Performance
            {
                Address = model.Address,
                CreateId = model.CreateId,
                ImageUrl = model.ImageUrl,
                Enabled = model.Enabled,
                ShowTime = model.ShowTime,
                Thumb = model.Thumb,
                Title = model.Title,
                Content = model.Content,
                CreateTime = model.CreateTime,
                Video = model.Video
            };
            Db.Entry(item).State= EntityState.Added;
            var result = await Db.SaveChangesAsync();
            if (result > 0) return item.Id;
            throw new ResultException(-501,"创建演出数据失败");
        }

        public async Task<int> UpdateAsync(PerformanceModel model)
        {
            var performance = await Db.Performances.FindAsync(model.Id);
            if (performance == null)
            {
                throw new ResultException(-404,"演出数据不存在");
            }

            performance.Title = model.Title;
            performance.ImageUrl = model.ImageUrl;
            performance.ShowTime = model.ShowTime;
            performance.Address = model.Address;
            performance.Thumb = model.Thumb;
            performance.UpdateId = model.UpdateId;
            performance.UpdateTime = model.UpdateTime;
            performance.Video = model.Video;
            performance.Content = model.Content;

            Db.Entry(performance).State= EntityState.Modified;
            var result = await Db.SaveChangesAsync();
            if (result > 0) return performance.Id;
            throw new ResultException(-501,"更新演出数据失败");
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var performance = await Db.Performances.FindAsync(id);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            if (!performance.Enabled) return true;
            performance.Enabled = false;
            Db.Entry(performance).State = EntityState.Modified;
            return (await Db.SaveChangesAsync()) > 0;
        }

        public async Task<bool> ResumeAsync(int id)
        {
            var performance = await Db.Performances.FindAsync(id);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            if (performance.Enabled) return true;
            performance.Enabled = true;
            Db.Entry(performance).State = EntityState.Modified;
            return (await Db.SaveChangesAsync()) > 0;
        }

        public async Task<ResultMessage<List<PerformanceModel>>> SearchAsync(string title, DateTime start, DateTime end, int pageIndex, int pageSize)
        {
            var query = Db.Performances.Include(a=>a.CreateUser).Include(a=>a.UpdateUser)
                .AsNoTracking().Where(a=>a.CreateTime >=start && a.CreateTime <= end);
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(a => a.Title.Contains(title));
            }
            var total =await query.CountAsync();
            var list = await query.OrderBy(a=>a.Id).Skip((pageIndex - 1)*pageSize).Take(pageSize)
                .Select(a=>new PerformanceModel
                {
                    Id = a.Id,
                    Title = a.Title,
                    Thumb = a.Thumb,
                    ImageUrl = a.ImageUrl,
                    Address = a.Address,
                    ShowTime = a.ShowTime,
                    Enabled = a.Enabled,
                    CreateId = a.CreateId,
                    CreateUser = a.CreateUser.RealName,
                    UpdateId = a.UpdateId,
                    UpdateUser = a.UpdateUser.RealName
                })
                .ToListAsync();
            return new ResultMessage<List<PerformanceModel>>(list,total);
        }

        public async Task<List<PerformanceModel>> GetAllPerformancesAsync()
        {
            var query = Db.Performances
                .AsNoTracking().Where(a => a.Enabled);
            
            var list = await query.Select(a => new PerformanceModel
                {
                    Id = a.Id,
                    Title = a.Title,
                    Thumb = a.Thumb,
                    ImageUrl = a.ImageUrl,
                    Address = a.Address,
                    ShowTime = a.ShowTime
                })
                .ToListAsync();
            return list;
        }

        public async Task<PerformanceModel> GetAsync(int id)
        {
            var performance = await Db.Performances.Include(a => a.CreateUser).Include(a => a.UpdateUser)
                .AsNoTracking().FirstOrDefaultAsync(a => a.Id == id);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            return new PerformanceModel
            {
                Id = performance.Id,
                Title = performance.Title,
                Thumb = performance.Thumb,
                ImageUrl = performance.ImageUrl,
                Address = performance.Address,
                ShowTime = performance.ShowTime,
                Enabled = performance.Enabled,
                Content = performance.Content,
                Video = performance.Video,
                CreateId = performance.CreateId,
                CreateUser = performance.CreateUser.RealName,
                UpdateId = performance.UpdateId,
                UpdateUser = performance.UpdateUser?.RealName
            };
        }

        public async Task<bool> SubscribeAsync(int performanceId, string openId)
        {
            var performance = await Db.Performances.FindAsync(performanceId);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            var subscribe =
                await
                    Db.Subscribings.FirstOrDefaultAsync(
                        a => a.PerformanceId == performanceId && a.WechatOpenId == openId);
            if (subscribe != null)
            {
                return true;
            }
            subscribe = new Subscribing
            {
                PerformanceId = performanceId,
                WechatOpenId = openId,
                Noticed = false,
                CreateTime = DateTime.Now
            };
            Db.Entry(subscribe).State= EntityState.Added;
            return (await Db.SaveChangesAsync()) > 0;
        }

        public async Task<bool> UnsubscribeAsync(int performanceId, string openId)
        {
            var performance = await Db.Performances.FindAsync(performanceId);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            var subscribe =
                await
                    Db.Subscribings.FirstOrDefaultAsync(
                        a => a.PerformanceId == performanceId && a.WechatOpenId == openId);
            if (subscribe == null)
            {
                return true;
            }
            Db.Entry(subscribe).State = EntityState.Deleted;
            return (await Db.SaveChangesAsync()) > 0;
        }

        public async Task<ResultMessage<List<SubscribingModel>>> SearchSubscribingsAsync(int performanceId, DateTime start, DateTime end, int pageIndex, int pageSize)
        {
            var query = Db.Subscribings.AsNoTracking().Where(a => a.PerformanceId == performanceId
                                                                  && a.CreateTime >= start && a.CreateTime <= end);
            var count = await query.CountAsync();
            var result = await query.Skip((pageIndex - 1)*pageSize).Skip(pageSize)
                .Select(a => new SubscribingModel
                {
                    Id = a.Id,
                    PerformanceId = a.PerformanceId,
                    WechatOpenId = a.WechatOpenId,
                    WecharNickname = a.WecharNickname,
                    CreateTime = a.CreateTime,
                    Noticed = a.Noticed
                }).ToListAsync();
            return new ResultMessage<List<SubscribingModel>>(result, count);
        }

        public async Task<bool> SetContentAsync(int performanceId, string content)
        {
            var performance = await Db.Performances.FindAsync(performanceId);
            if (performance == null)
            {
                throw new ResultException(-404, "演出数据不存在");
            }
            performance.Content = content;
            Db.Entry(performance).State = EntityState.Modified;

            return await Db.SaveChangesAsync() > 0;
        }
    }
}